package org.ecc.android.validations.library;

import java.util.ArrayList;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

public class EditTextValidator {

	private ArrayList<ValidationModel> validationModels;

	private View button;

	private Context context;

	public EditTextValidator(Context context) {
		this(context, null);
	}

	public EditTextValidator(Context context, View button) {

		init(context, button);
	}

	private void init(Context context, View button) {
		this.context = context;
		this.button = button;
		validationModels = new ArrayList<>();
	}

	public EditTextValidator setButton(View button) {
		this.button = button;
		return this;
	}

	public EditTextValidator add(ValidationModel validationModel) {
		validationModels.add(validationModel);
		return this;
	}

	public EditTextValidator execute() {
		for (final ValidationModel validationModel : validationModels) {
			if (validationModel.getEditText() == null) {
				return this;
			}
			validationModel.getEditText().addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					setEnabled();
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {
				}
			});
		}

		setEnabled();

		return this;
	}

	private void setEnabled() {
		for (final ValidationModel validationModel : validationModels) {
			if (button != null) {
				if (validationModel.isTextEmpty()) {// 如果有一个是空的，button直接不可点击
					button.setEnabled(false);
					return;
				} else {
					if (!button.isEnabled()) {
						button.setEnabled(true);
					}
				}
			}
		}
	}

	public ValidateResult validate() {
		ValidateResult result = new ValidateResult();
		ArrayList<Errors> errorses = new ArrayList<>();
		result.setErrors(false);
		for (ValidationModel validationModel : validationModels) {
			if (validationModel.getValidationExecutor() == null || validationModel.getEditText() == null) {
				continue;
			}
			if (!validationModel.getValidationExecutor().doValidate(context, validationModel.getEditText().getText().toString())) {
				Errors errors = new Errors();
				errors.setMessage(validationModel.getErrorMessage());
				errorses.add(errors);
			}
		}
		if(errorses.size() > 0){
			result.setErrors(true);
			result.setErrorsList(errorses);
		}
		return result;
	}

	public View getButton() {
		return button;
	}

}
